package com.byd.android.MusicPlayer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.byd.android.agreement.InstructionList;
import com.byd.android.agreement.message.Music;
import com.byd.android.mediaplayer.BaseActivity;
import com.byd.android.mediaplayer.R;

import java.util.ArrayList;
import java.util.List;


public class MusicPlayer extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "MusicPlayer";

    private List<Music> musicList = new ArrayList<>();

    private int currentMusicIndex = -1;

    private ListView musicLv;

    private Intent intent;

    private ImageButton backIb;

    private TextView musicNameTv;

    private TextView musicArtistTv;

    private TextView musicCurrentProgressTv;

    private TextView musicDurationTv;

    private ImageView musicImageIv;

    private SeekBar musicSeekSb;

    private ImageButton previousIb;

    private ImageButton controlIb;

    private ImageButton nextIb;

    private MusicImageTask musicImageTask;

    private View viewSingle, viewMusicList;

    private ViewPager viewPager;

    private List<View> viewList;

    private boolean isFirstCreate = true;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case InstructionList.ORDER.ORDER_PLAY:
                case InstructionList.ORDER.ORDER_PREVIOUS:
                case InstructionList.ORDER.ORDER_NEXT:
                    currentMusicIndex = msg.arg1;
                    upGrateMusic(currentMusicIndex);
                    break;
                case InstructionList.ORDER.ORDER_CONTINUE:
                    currentMusicIndex = msg.arg1;
                    controlIb.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause1, null));
                    break;
                case InstructionList.ORDER.ORDER_PAUSE:
                    currentMusicIndex = msg.arg1;
                    controlIb.setImageDrawable(getResources().getDrawable(R.drawable.ic_play1, null));
                    break;
                case InstructionList.ORDER.ORDER_CURRENTDURATION:
                    int position = msg.arg1;
                    currentMusicIndex = msg.arg2;
                    int duration = musicList.get(currentMusicIndex).getDuration();
                    int progress = position * 100 / duration;
                    musicSeekSb.setProgress(progress);
                    musicCurrentProgressTv.setText(getPositionText(position));
                    break;
                case InstructionList.ORDER.ORDER_ISSTOP:
                    currentMusicIndex++;
                    upGrateMusic(currentMusicIndex);
                    break;
                case InstructionList.ORDER.ORDER_BACK:
                    mServiceBinder.stop(/* reset */ true);
                    onBackPressed();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_playface);
        init();
        Log.d(TAG, "onCreate: bind is success");
    }

    //设置适配器
    private void setMusicAdapter() {
        try {
            musicList = mServiceBinder.getMusicList();
            MusicAdapter musicAdapter = new MusicAdapter(MusicPlayer.this, musicList);
            musicLv.setAdapter(musicAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置viewList监听和进度条监听
    private void setListListener() {
        try {
            musicLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                    currentMusicIndex = position;
                    Log.d(TAG, "onItemClick: click is " + currentMusicIndex);
                    upGrateMusic(currentMusicIndex);
                    mServiceBinder.play(currentMusicIndex);
                    //此处播放音乐，传递给Service；
                }
            });

            musicSeekSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    int duration = musicList.get(currentMusicIndex).getDuration();
                    mServiceBinder.seek(seekBar.getProgress() * duration / 100);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.music_control:
                if (currentMusicIndex == -1) {
                    currentMusicIndex = 0;
                    upGrateMusic(currentMusicIndex);
                    mServiceBinder.play(currentMusicIndex);
                    //此处控制按钮变为暂停
                } else {
                    controlMusic();
                }
                break;
            case R.id.music_previous:
                mServiceBinder.previous(currentMusicIndex);
                if (currentMusicIndex == 0) {
                    currentMusicIndex = musicList.size() - 1;
                    upGrateMusic(currentMusicIndex);
                } else {
                    currentMusicIndex--;
                    upGrateMusic(currentMusicIndex);
                }
                break;
            case R.id.music_next:
                mServiceBinder.next(currentMusicIndex);
                if (currentMusicIndex == musicList.size() - 1) {
                    currentMusicIndex = 0;
                    upGrateMusic(currentMusicIndex);
                } else {
                    currentMusicIndex++;
                    upGrateMusic(currentMusicIndex);
                }
                break;
            case R.id.music_back:
                mServiceBinder.stop(/* reset */ true);
                onBackPressed();

                //unbindService(connectToService());
                //此处退出音乐播放器,返回主页
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unbindService(connection);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //   initMediaPlayer();
                } else {
                    Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }

    //获取权限
    private void confirmPermission() {
        if (ContextCompat.checkSelfPermission(MusicPlayer.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MusicPlayer.this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            Log.d("init", "is ready");
            //  getSong();
        }
    }


    //更新界面UI
    private void upGrateMusic(int Index) {
        musicDurationTv.setText(getPositionText(musicList.get(Index).getDuration()) + "");
        musicNameTv.setText(musicList.get(Index).getMusicName() + "");
        musicArtistTv.setText(musicList.get(Index).getArtist() + "");
        controlIb.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause1, null));
        musicImageTask = new MusicImageTask(mServiceBinder.sendMusicImage(Index), musicImageIv);
        musicImageTask.execute(mServiceBinder.sendMusicImage(Index));
        Log.d(TAG, "upGrateMusic: musicImageTask.execute");

    }

    //初始化
    private void init() {
        confirmPermission();
        backIb = (ImageButton) findViewById(R.id.music_back);
        musicCurrentProgressTv = (TextView) findViewById(R.id.music_currentprogress);
        musicDurationTv = (TextView) findViewById(R.id.muisc_duration);
        musicSeekSb = (SeekBar) findViewById(R.id.seek_bar);
        nextIb = (ImageButton) findViewById(R.id.music_next);
        previousIb = (ImageButton) findViewById(R.id.music_previous);
        controlIb = (ImageButton) findViewById(R.id.music_control);
        backIb.setOnClickListener(this);
        nextIb.setOnClickListener(this);
        previousIb.setOnClickListener(this);
        controlIb.setOnClickListener(this);
        //声明viewapger
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        LayoutInflater inflater = getLayoutInflater();
        viewSingle = inflater.inflate(R.layout.music_singleface, null);
        viewMusicList = inflater.inflate(R.layout.muisc_list, null);
        viewList = new ArrayList<View>();
        viewList.add(viewSingle);
        viewList.add(viewMusicList);
        //viewpager中的声明
        musicLv = (ListView) viewMusicList.findViewById(R.id.list_view);
        musicNameTv = (TextView) viewSingle.findViewById(R.id.music_nameface);
        musicArtistTv = (TextView) viewSingle.findViewById(R.id.music_artistface);
        musicImageIv = (ImageView) viewSingle.findViewById(R.id.music_image);


        PagerAdapter pagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return viewList.size();
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(viewList.get(position));
                return viewList.get(position);
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(viewList.get(position));
            }
        };
        viewPager.setAdapter(pagerAdapter);

//        intent = new Intent(MusicPlayer.this, MediaService.class);
//        bindService(intent, connection, Context.BIND_AUTO_CREATE);

        setListListener();      //设置监听器

    }

    private void controlMusic() {
        if (!mServiceBinder.playing()) {
            //          controlIb.setText("暂停");
            controlIb.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause1, null));

            mServiceBinder.play();
        } else {
            mServiceBinder.pause();
            //         controlBu.setText("播放");
            controlIb.setImageDrawable(getResources().getDrawable(R.drawable.ic_play1, null));


        }
    }

    public static String getPositionText(int position) {
        String text = "";
        position /= 1000;
        if (position / 60 >= 10) {
            text += position / 60;  // minutes
        } else {
            text += "0";
            text += position / 60;  //
        }
        text += ":";
        if (position % 60 >= 10) {  //seconds
            text += position % 60;
            return text;
        } else {
            text += "0";
            text += position % 60;
            return text;
        }

    }

    @Override
    protected void sendHandlerToService() {
        mServiceBinder.sendHandler(handler);
        mServiceBinder.getMode(InstructionList.MODE.MODE_MUSIC);

        setMusicAdapter();
    }

}
